/*
 * Copyright 2011 Vlad Goldman.  All rights reserved.
  
   This file is part of GooOutSync - Google Outlook Sync application
  
    Project page: http://goooutsync.googlecode.com

    GooOutSync is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    GooOutSync is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with GooOutSync.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.vgold.goooutsync;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

import javax.swing.AbstractButton;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import org.apache.log4j.Logger;

import com.vgold.goooutsync.GooOutSyncPreferences.Prefs;

public class GooOutSettings extends JFrame implements ActionListener {
	// private int timeBetweenSync;
	private Logger logger;
	private GooutSyncGUI gui;
	JTabbedPane tabbedPane;
	private static final String version = "1.2";
	private GooOutSyncPreferences preferences;

	private JTextField googleUser;
	private JPasswordField googlePassword;
	private JTextField timeBetweenSync;
	private JTextField proxyServer;
	private JTextField proxyPort;
	private JTextField proxyUser;
	private JTextField proxyPassword;
	private GoogleCredentials googleCredentials;

	public GooOutSettings(GooutSyncGUI gui) throws GooOutSyncException {
		super("GooOutSync v" + version + " Settings");
		this.gui = gui;
		logger = Logger.getLogger(GooOutSettings.class);
		preferences = GooOutSyncPreferences.getGooOutSyncPreferences();
		googleCredentials = GoogleCredentials.getGoogleCredentials();
		this.setIconImage(gui.getTrayIcon());
		this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
		// Add content to the window.
		this.add(createSettingsPanel(), BorderLayout.CENTER);
		this.pack();
		this.setLocationRelativeTo(null);
		// TODO Auto-generated constructor stub
	}

	private JPanel createSettingsPanel() {
		JPanel panel = new JPanel(new GridLayout(1, 1));
		panel.setPreferredSize(new Dimension(400, 300));
		panel.setBackground(Color.YELLOW);
		tabbedPane = new JTabbedPane(JTabbedPane.LEFT);
		tabbedPane.setBackground(Color.ORANGE);
		// ImageIcon icon =gui.getTrayIcon();

		JComponent panel1 = makeAccountSettingsPanel();
		tabbedPane.addTab("Account Settings", panel1);
		tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);

		JComponent panel2 = makeSyncSettingsPanel();
		tabbedPane.addTab("Sync Settings", panel2);
		tabbedPane.setMnemonicAt(1, KeyEvent.VK_2);

		JComponent panel3 = makeAdvancedPanel();
		tabbedPane.addTab("Advanced", panel3);
		tabbedPane.setMnemonicAt(2, KeyEvent.VK_3);
		JComponent panel4 = makeExperimentPanel();
		tabbedPane.addTab("Experimental", panel4);
		tabbedPane.setMnemonicAt(2, KeyEvent.VK_3);
		JComponent panel5 = createAboutPanel();
		tabbedPane.addTab("About", panel5);
		tabbedPane.setMnemonicAt(3, KeyEvent.VK_4);

		// Add the tabbed pane to this panel.
		panel.add(tabbedPane);
		// The following line enables to use scrolling tabs.
		tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
		return panel;
	}

	private JComponent makeAdvancedPanel() {
		JPanel panel = new JPanel(new GridBagLayout());
		panel.setBackground(Color.WHITE);
		GridBagConstraints c = new GridBagConstraints();
		c.gridx = 0;
		c.gridy = 0;
		c.fill = GridBagConstraints.HORIZONTAL;
		c.anchor = GridBagConstraints.PAGE_START;
		panel.add(createLabelPanel("Proxy Server"), c);
		c.gridx = 1;
		c.gridy = 0;
		panel.add(
				createInputTextPanel(
						preferences
								.getPreference(GooOutSyncPreferences.Prefs.proxy_server),
						GooOutSyncPreferences.Prefs.proxy_server), c);
		c.gridx = 0;
		c.gridy = 1;
		panel.add(createLabelPanel("Proxy Port"), c);
		c.gridx = 1;
		c.gridy = 1;
		panel.add(
				createInputTextPanel(preferences
						.getPreference(GooOutSyncPreferences.Prefs.proxy_port),
						GooOutSyncPreferences.Prefs.proxy_port), c);
		c.gridx = 1;
		c.gridy = 2;
		c.anchor = GridBagConstraints.LAST_LINE_END;
		panel.add(createButtonPanel("Save", "SaveAdvancedSettings"), c);
		return panel;
	}

	private JComponent makeSyncSettingsPanel() {
		JPanel panel = new JPanel(new GridBagLayout());
		panel.setBackground(Color.WHITE);
		GridBagConstraints c = new GridBagConstraints();
		c.gridx = 0;
		c.gridy = 0;
		c.fill = GridBagConstraints.HORIZONTAL;
		c.anchor = GridBagConstraints.PAGE_START;
		panel.add(createLabelPanel("Time between sync (minutes)"), c);
		c.gridx = 1;
		c.gridy = 0;
		panel.add(
				createInputTextPanel(
						preferences
								.getPreference(GooOutSyncPreferences.Prefs.time_between_sync),
						GooOutSyncPreferences.Prefs.time_between_sync), c);
		c.gridx = 1;
		c.gridy = 4;
		c.anchor = GridBagConstraints.LAST_LINE_END;
		panel.add(createButtonPanel("Save", "SaveSyncSettings"), c);
		return panel;
	}

	private JComponent makeAccountSettingsPanel() {
		JPanel panel = new JPanel(new GridBagLayout());
		panel.setBackground(Color.WHITE);
		GridBagConstraints c = new GridBagConstraints();
		c.gridx = 0;
		c.gridy = 0;
		c.fill = GridBagConstraints.HORIZONTAL;
		c.anchor = GridBagConstraints.PAGE_START;
		panel.add(createLabelPanel("Google Username"), c);
		c.gridx = 1;
		c.gridy = 0;
		panel.add(
				createInputTextPanel(googleCredentials.getUser(),
						GooOutSyncPreferences.Prefs.google_username), c);
		c.gridx = 0;
		c.gridy = 1;
		panel.add(createLabelPanel("Google Password"), c);
		c.gridx = 1;
		c.gridy = 1;
		panel.add(
				createInputPasswordTextPanel(googleCredentials.getPassword(),
						GooOutSyncPreferences.Prefs.google_password), c);
		c.gridx = 1;
		c.gridy = 2;
		c.anchor = GridBagConstraints.LAST_LINE_END;
		panel.add(createButtonPanel("Save", "SaveGoogleSettings"), c);
		return panel;
	}

	private JComponent makeExperimentPanel() {
		GridLayout experimentLayout = new GridLayout(0, 2);
		JPanel panel = new JPanel(experimentLayout);
		JPanel buttonPanel = createButtonPanel("Clear GMail Contacts",
				"ClearGmail");
		panel.setBackground(Color.WHITE);
		panel.add(buttonPanel);
		return panel;
	}

	private JPanel createLabelPanel(String text) {
		JPanel panel = new JPanel(new BorderLayout());
		panel.setBackground(Color.WHITE);
		JLabel label = new JLabel(text);
		panel.add(label, BorderLayout.CENTER);
		panel.setPreferredSize(label.getPreferredSize());
		return panel;
	}

	private JPanel createInputTextPanel(String text, Prefs pref) {
		JPanel panel = new JPanel(new BorderLayout());
		JTextField inputField = new JTextField(text);
		switch (pref) {
		case google_username:
			googleUser = inputField;
			break;
		case time_between_sync:
			timeBetweenSync = inputField;
			break;
		case proxy_server:
			proxyServer = inputField;
			break;
		case proxy_port:
			proxyPort = inputField;
			break;
		case proxy_user:
			proxyUser = inputField;
			break;
		case proxy_password:
			proxyPassword = inputField;
			break;
		}
		panel.add(inputField, BorderLayout.CENTER);
		panel.setPreferredSize(inputField.getPreferredSize());
		return panel;
	}

	private JPanel createInputPasswordTextPanel(String text, Prefs pref) {
		JPanel panel = new JPanel(new BorderLayout());
		JPasswordField passwordField = new JPasswordField(text);
		switch (pref) {
		case google_password:
			googlePassword = passwordField;
			break;
		case proxy_password:
			proxyPassword = passwordField;
			break;
		}
		panel.add(passwordField, BorderLayout.CENTER);
		panel.setPreferredSize(new Dimension(100, 20));
		return panel;
	}

	private JPanel createButtonPanel(String button, String command) {
		JPanel buttonPanel = new JPanel(false);
		buttonPanel.setBackground(Color.WHITE);
		JButton b1 = new JButton(button);
		b1.setVerticalTextPosition(AbstractButton.CENTER);
		b1.setHorizontalTextPosition(AbstractButton.LEADING); // aka LEFT, for
																// left-to-right
																// locales
		// b1.setMnemonic(KeyEvent.VK_D);
		b1.setActionCommand(command);
		b1.addActionListener(this);
		// b1.setPreferredSize(new Dimension(100, 30));
		// JLabel l1=new JLabel(text);
		// l1.setPreferredSize(new Dimension(30, 15));
		buttonPanel.add(b1);

		// buttonPanel.add(l1);
		buttonPanel.setPreferredSize(new Dimension(100, 30));
		return buttonPanel;
	}

	protected JComponent makeTextPanel(String text) {
		JPanel panel = new JPanel();

		JLabel filler = new JLabel(text);
		filler.setHorizontalAlignment(JLabel.CENTER);
		panel.setLayout(new GridLayout(1, 1));
		panel.add(filler);
		return panel;
	}

	private JPanel createAboutPanel() {
		JPanel infoPnlBody = new JPanel();
		JTextArea textArea = new JTextArea();
		infoPnlBody.setLayout(new BorderLayout());
		textArea.setLineWrap(true);
		textArea.setWrapStyleWord(true);
		textArea.setEditable(false);
		textArea.setPreferredSize(new Dimension(200, 300));
		textArea.setBorder(BorderFactory.createCompoundBorder(BorderFactory
				.createCompoundBorder(
						BorderFactory.createTitledBorder("About"),
						BorderFactory.createEmptyBorder(5, 5, 5, 5)), textArea
				.getBorder()));
		textArea.setFont(new Font("SansSerif", Font.PLAIN, 12));
		textArea.append("Google Outlook Sync \n\n");
		textArea.append("Copyright 2011 Vlad Goldman. All rights reserved.\n\n");
		textArea.append("Project page: http://goooutsync.googlecode.com\n\n");
		textArea.append("This program comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome to redistribute it under certain conditions;\n\n");
		// textArea.append("\n");
		// textArea.append("");
		infoPnlBody.add(textArea, BorderLayout.CENTER);
		infoPnlBody.repaint();
		return infoPnlBody;
	}

	public void switchToAboutTab() {
		tabbedPane.setSelectedIndex(tabbedPane.indexOfTab("About"));
	}

	public void actionPerformed(ActionEvent e) {
		if ("ClearGmail".equals(e.getActionCommand())) {
			int confirm = JOptionPane
					.showConfirmDialog(
							this,
							"Are you sure you want to clear all GMail Contacts synced by GooOutSync?",
							"Warning", JOptionPane.YES_NO_OPTION);
			if (confirm == JOptionPane.YES_OPTION) {
				gui.deleteGoogleContactsWithOutlookID();
			}
		} else if ("SaveGoogleSettings".equals(e.getActionCommand())) {
			logger.info("Saving Google Credentials... " + googleUser.getText()
					+ ":" + new String(googlePassword.getPassword()));
			try {
				googleCredentials.setCredentials(googleUser.getText(),
						new String(googlePassword.getPassword()));
			} catch (GooOutSyncException e1) {
				gui.setSyncFailIcon();
				gui.displayErrorMessage(
						"GooOutSync failed saving Google credentials ",
						e1.getMessage());
				gui.setToolTip("GooOutSync failed saving Google credentials: "
						+ e1.getMessage());
				logger.error("GooOutSync failed saving Google credentials", e1);
			}
		} // SaveAdvancedSettings
		else if ("SaveSyncSettings".equals(e.getActionCommand())) {
			preferences.setPreference(
					GooOutSyncPreferences.Prefs.time_between_sync,
					timeBetweenSync.getText());
			gui.setTimerDelay(Integer.valueOf(timeBetweenSync.getText()));
		} else if ("SaveAdvancedSettings".equals(e.getActionCommand())) {
			preferences.setPreference(GooOutSyncPreferences.Prefs.proxy_server,
					proxyServer.getText());
			preferences.setPreference(GooOutSyncPreferences.Prefs.proxy_port,
					proxyPort.getText());
		}
	}
}
